const Encryption = require('../utils/encryption');
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    openid: {
      type: DataTypes.STRING(128),
      allowNull: false,
      unique: true,
      comment: '微信用户唯一标识(加密存储)',
      set(value) {
        this.setDataValue('openid', Encryption.encrypt(value));
      },
      get() {
        const encrypted = this.getDataValue('openid');
        if (!encrypted) return null;
        try {
          return Encryption.decrypt(encrypted);
        } catch (err) {
          console.error('解密openid失败:', err);
          return null;
        }
      }
    },
    nickname: {
      type: DataTypes.STRING(64),
      comment: '微信昵称'
    },
    avatar: {
      type: DataTypes.STRING(255),
      comment: '微信头像URL'
    },
    subscribeTime: {
      type: DataTypes.DATE,
      comment: '关注公众号时间'
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '状态：0-禁用 1-正常'
    },
    quietHoursStart: {
      type: DataTypes.STRING(5),
      defaultValue: '23:00',
      comment: '免打扰开始时间(HH:mm)'
    },
    quietHoursEnd: {
      type: DataTypes.STRING(5),
      defaultValue: '07:00',
      comment: '免打扰结束时间(HH:mm)'
    }
  }, {
    tableName: 'users',
    timestamps: true,
    paranoid: true,
    comment: '微信用户信息表'
  });

  return User;
};